package com.abc.robot01.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import com.abc.robot01.R
import kotlin.math.abs

class DraggableConstraintLayout2 @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    val TAG="DraggableConstraintLayout2"

    private var lastX = 0f
    private var deltaX = 0f
    private var velocityTracker: VelocityTracker? = null
    private val minFlingVelocity: Int
    private val maxFlingVelocity: Int

    init {
        val viewConfiguration = ViewConfiguration.get(context)
        minFlingVelocity = viewConfiguration.scaledMinimumFlingVelocity
        maxFlingVelocity = viewConfiguration.scaledMaximumFlingVelocity
    }

    private var root2 :View?=null
//    private  lateinit  var close :View
//    private lateinit var sp: View
    private var lastY = 0f

    private var contentVisible = true

    private lateinit var childConstraintLayout: ConstraintLayout

    override fun onFinishInflate() {
        super.onFinishInflate()
        // Assuming the child is a ConstraintLayout and there's only one child
        if (childCount == 1 && getChildAt(0) is ConstraintLayout) {
            childConstraintLayout = getChildAt(0) as ConstraintLayout
        } else {
            throw IllegalStateException("DraggableConstraintLayout2 must have a single ConstraintLayout child")
        }

        findViewById<View>(R.id.open).setOnClickListener {
            Log.e(TAG, "open  setOnClickListener");
        }

        findViewById<View>(R.id.close).setOnClickListener {
            Log.e(TAG, "close  setOnClickListener");
        }


//        close =  findViewById<View>(R.id.close)
//           val  toggle = findViewById<View>(R.id.toggle)
////          sp = findViewById<View>(R.id.sp)
//        val  onClick = {
//            if(root2.visibility== VISIBLE){
//                Log.e(TAG,"onclick INVISIBLE")
//                root2.visibility = INVISIBLE
//                contentVisible = false
//            }
//            else{
//                root2.visibility = VISIBLE
//                contentVisible = true
//                Log.e(TAG,"onclick VISIBLE")
//            }
//        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        measureChild(childConstraintLayout, widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            resolveSize(childConstraintLayout.measuredWidth, widthMeasureSpec),
            resolveSize(childConstraintLayout.measuredHeight, heightMeasureSpec)
        )
    }

    override fun onLayout(p0: Boolean, l: Int, t: Int, r: Int, b: Int) {
        // Layout the ConstraintLayout
        childConstraintLayout.layout(0, 0, childConstraintLayout.measuredWidth, childConstraintLayout.measuredHeight)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
       //左上角全部不拦截
        if(ev.rawX<=150 && ev.rawY<=150){
            Log.e(TAG,"onInterceptTouchEvent return false")
            return false
        }
        if(closed)
        {
            if(ev.rawX>90)
            { return false}
            else{
                closed = false
                }
        }

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = ev.rawX
                velocityTracker = VelocityTracker.obtain()
                velocityTracker?.addMovement(ev)
            }
            MotionEvent.ACTION_MOVE -> {
                val deltaX = ev.rawX - lastX
                if (abs(deltaX) > ViewConfiguration.get(context).scaledTouchSlop) {
                    return true
                }
            }
        }
        return super.onInterceptTouchEvent(ev)
    }

    private var  closed= true

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //左上角全部不拦截
        if(event.rawX<=150 && event.rawY<=150){
            Log.e(TAG,"onTouchEvent return false")
            return false
        }

        if(closed)
        {
            if(event.rawX>90)
            { return false}
            else{
                closed = false
            }
        }
        velocityTracker?.addMovement(event)
        when (event.action) {
            MotionEvent.ACTION_MOVE -> {
                 deltaX = event.rawX - lastX
                lastX = event.rawX

                // Move the child ConstraintLayout horizontally
                childConstraintLayout.translationX += deltaX
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                velocityTracker?.computeCurrentVelocity(1000, maxFlingVelocity.toFloat())
                val velocityX = velocityTracker?.xVelocity ?: 0f
                //向右滑动,translationX为0
                if(deltaX > 0 ){
                    val targetX = 0f
                    // Animate the translationX property using ObjectAnimator
                    ObjectAnimator.ofFloat(
                        childConstraintLayout,
                        "translationX",
                        childConstraintLayout.translationX,
                        targetX
                    ).apply {
                        duration = 1000L // Animation duration in milliseconds
                        interpolator = DecelerateInterpolator()
                        addListener(object : AnimatorListenerAdapter() {
                            override fun onAnimationEnd(animation: Animator) {
                                super.onAnimationEnd(animation)
                                findViewById<View>(R.id.open).visibility= INVISIBLE
                                findViewById<View>(R.id.close).visibility= VISIBLE
                                closed = false
                                Log.e(TAG,"closed:"+closed)
                            }
                        })
                        start()
                    }
                }
                //向左滑动,translationX最小为它的0-width.
                if(deltaX < 0 ){
                    val targetX = -width.toFloat() + 148
                    // Animate the translationX property using ObjectAnimator
                    ObjectAnimator.ofFloat(
                        childConstraintLayout,
                        "translationX",
                        childConstraintLayout.translationX,
                        targetX
                    ).apply {
                        duration = 1000L // Animation duration in milliseconds
                        interpolator = DecelerateInterpolator()
                        addListener(object : AnimatorListenerAdapter() {
                            override fun onAnimationEnd(animation: Animator) {
                                super.onAnimationEnd(animation)
                                findViewById<View>(R.id.open).visibility= VISIBLE
                                findViewById<View>(R.id.close).visibility= INVISIBLE
                                closed = true
                                Log.e(TAG,"closed:"+closed)
                            }
                        })
                        start()
                    }
                }
                velocityTracker?.recycle()
                velocityTracker = null
            }
        }
        return true
    }
}
